package cn.hpclub.server.util;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.hpclub.server.bean.SystemConfig.WatermarkPosition;

/**
 * 工具类 - 图片处理
 * 
 */

public class ImageUtil{

    private static final Logger logger = LoggerFactory.getLogger(ImageUtil.class);

    /**
     * 图片缩放(图片等比例缩放为指定大小，空白部分以白色填充)
     * 
     * @param srcBufferedImage
     *            源图片
     * @param destFile
     *            缩放后的图片文件
     */
    public static void zoom(BufferedImage srcBufferedImage, File destFile, int destHeight, int destWidth){
        try{
            int imgWidth = destWidth;
            int imgHeight = destHeight;
            int srcWidth = srcBufferedImage.getWidth();
            int srcHeight = srcBufferedImage.getHeight();
            if(srcHeight >= srcWidth){
                imgWidth = (int)Math.round(((destHeight * 1.0 / srcHeight) * srcWidth));
            } else{
                imgHeight = (int)Math.round(((destWidth * 1.0 / srcWidth) * srcHeight));
            }
            BufferedImage destBufferedImage = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics2D = destBufferedImage.createGraphics();
            graphics2D.setBackground(Color.WHITE);
            graphics2D.clearRect(0, 0, destWidth, destHeight);
            graphics2D.drawImage(srcBufferedImage.getScaledInstance(imgWidth, imgHeight, Image.SCALE_SMOOTH),
                                 (destWidth / 2) - (imgWidth / 2), (destHeight / 2) - (imgHeight / 2), null);
            graphics2D.dispose();
            ImageIO.write(destBufferedImage, "JPEG", destFile);
        }
        catch(IOException e){
            e.printStackTrace();
        }
    }

    /**
     * 添加图片水印
     * 
     * @param srcBufferedImage
     *            需要处理的源图片
     * @param destFile
     *            处理后的图片文件
     * @param watermarkFile
     *            水印图片文件
     * 
     */
    public static void imageWatermark(BufferedImage srcBufferedImage, File destFile, File watermarkFile,
            WatermarkPosition watermarkPosition, int alpha){
        try{
            int srcWidth = srcBufferedImage.getWidth();
            int srcHeight = srcBufferedImage.getHeight();
            BufferedImage destBufferedImage = new BufferedImage(srcWidth, srcHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics2D = destBufferedImage.createGraphics();
            graphics2D.setBackground(Color.WHITE);
            graphics2D.clearRect(0, 0, srcWidth, srcHeight);
            graphics2D.drawImage(srcBufferedImage.getScaledInstance(srcWidth, srcHeight, Image.SCALE_SMOOTH), 0, 0,
                                 null);

            if(watermarkFile != null && watermarkFile.exists() && watermarkPosition != null
                    && watermarkPosition != WatermarkPosition.no){
                BufferedImage watermarkBufferedImage = ImageIO.read(watermarkFile);
                int watermarkImageWidth = watermarkBufferedImage.getWidth();
                int watermarkImageHeight = watermarkBufferedImage.getHeight();
                graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha / 100.0F));
                int x = 0;
                int y = 0;
                if(watermarkPosition == WatermarkPosition.topLeft){
                    x = 0;
                    y = 0;
                } else if(watermarkPosition == WatermarkPosition.topRight){
                    x = srcWidth - watermarkImageWidth;
                    y = 0;
                } else if(watermarkPosition == WatermarkPosition.center){
                    x = (srcWidth - watermarkImageWidth) / 2;
                    y = (srcHeight - watermarkImageHeight) / 2;
                } else if(watermarkPosition == WatermarkPosition.bottomLeft){
                    x = 0;
                    y = srcHeight - watermarkImageHeight;
                } else if(watermarkPosition == WatermarkPosition.bottomRight){
                    x = srcWidth - watermarkImageWidth;
                    y = srcHeight - watermarkImageHeight;
                }
                graphics2D.drawImage(watermarkBufferedImage, x, y, watermarkImageWidth, watermarkImageHeight, null);
            }
            graphics2D.dispose();
            ImageIO.write(destBufferedImage, "JPEG", destFile);
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 图片缩放并添加图片水印(图片等比例缩放为指定大小，空白部分以白色填充)
     * 
     * @param srcBufferedImage
     *            需要处理的图片
     * @param destFile
     *            处理后的图片文件
     * @param watermarkFile
     *            水印图片文件
     * 
     */
    public static void zoomAndWatermark(BufferedImage srcBufferedImage, File destFile, int destHeight, int destWidth,
            File watermarkFile, WatermarkPosition watermarkPosition, int alpha){
        try{
            int imgWidth = destWidth;
            int imgHeight = destHeight;
            int srcWidth = srcBufferedImage.getWidth();
            int srcHeight = srcBufferedImage.getHeight();
            if(srcHeight >= srcWidth){
                imgWidth = (int)Math.round(((destHeight * 1.0 / srcHeight) * srcWidth));
            } else{
                imgHeight = (int)Math.round(((destWidth * 1.0 / srcWidth) * srcHeight));
            }

            BufferedImage destBufferedImage = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics2D = destBufferedImage.createGraphics();
            graphics2D.setBackground(Color.WHITE);
            graphics2D.clearRect(0, 0, destWidth, destHeight);
            graphics2D.drawImage(srcBufferedImage.getScaledInstance(imgWidth, imgHeight, Image.SCALE_SMOOTH),
                                 (destWidth / 2) - (imgWidth / 2), (destHeight / 2) - (imgHeight / 2), null);
            if(watermarkFile != null && watermarkFile.exists() && watermarkPosition != null
                    && watermarkPosition != WatermarkPosition.no){
                BufferedImage watermarkBufferedImage = ImageIO.read(watermarkFile);
                int watermarkImageWidth = watermarkBufferedImage.getWidth();
                int watermarkImageHeight = watermarkBufferedImage.getHeight();
                graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha / 100.0F));
                int x = 0;
                int y = 0;
                if(watermarkPosition == WatermarkPosition.topLeft){
                    x = 0;
                    y = 0;
                } else if(watermarkPosition == WatermarkPosition.topRight){
                    x = destWidth - watermarkImageWidth;
                    y = 0;
                } else if(watermarkPosition == WatermarkPosition.center){
                    x = (destWidth - watermarkImageWidth) / 2;
                    y = (destHeight - watermarkImageHeight) / 2;
                } else if(watermarkPosition == WatermarkPosition.bottomLeft){
                    x = 0;
                    y = destHeight - watermarkImageHeight;
                } else if(watermarkPosition == WatermarkPosition.bottomRight){
                    x = destWidth - watermarkImageWidth;
                    y = destHeight - watermarkImageHeight;
                }
                graphics2D.drawImage(watermarkBufferedImage, x, y, watermarkImageWidth, watermarkImageHeight, null);
            }
            graphics2D.dispose();
            ImageIO.write(destBufferedImage, "JPEG", destFile);
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 获取图片文件的类型.
     * 
     * @param uploadFile
     *            图片文件对象.
     * @return 图片文件类型
     */
    public static String getImageFormatName(File uploadFile){
        try{
            ImageInputStream imageInputStream = ImageIO.createImageInputStream(uploadFile);
            Iterator<ImageReader> iterator = ImageIO.getImageReaders(imageInputStream);
            if(!iterator.hasNext()){
                return null;
            }
            ImageReader imageReader = (ImageReader)iterator.next();
            imageInputStream.close();
            return imageReader.getFormatName().toLowerCase();
        }
        catch(IOException e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @Title: getImageDetail 获取图片的信息（宽度，高度和尺寸）
     * @Description:TODO
     * @param imageFile
     *            图片文件A
     * @return Map<String,Long>
     */
    public static Map<String, Long> getImageSize(File imageFile){
        Map<String, Long> map = new HashMap<String, Long>(3);
        try{
            FileInputStream fis = new FileInputStream(imageFile);
            BufferedImage buff = ImageIO.read(imageFile);
            map.put("imgWidth", buff.getWidth() * 1L);
            map.put("imgHeight", buff.getHeight() * 1L);
            map.put("imgSize", imageFile.length());
            fis.close();
        }
        catch(FileNotFoundException e){
            logger.error("所给的图片文件" + imageFile.getPath() + "不存在！计算图片尺寸大小信息失败！", e.getMessage());
        }
        catch(IOException e){
            logger.error("计算图片" + imageFile.getPath() + "尺寸大小信息失败！", e.getMessage());
        }
        return map;
    }

    /**
     * @Title: cut 剪切图片
     * @Description:TODO
     * @param srcpath
     *            图片原始路径
     * @param subpath
     *            剪切后的图片路径
     * @param x
     *            起始x坐标
     * @param y
     *            起始y坐标
     * @param width
     *            剪切后图像的宽度
     * @param height
     *            剪切后图像的高度
     * @param suffix
     *            图片后缀
     * @throws IOException
     *             void
     */
    public final static void cut(String srcpath, String subpath, int x, int y, int width, int height, String suffix)
            throws IOException{
        FileInputStream is = null;
        ImageInputStream iis = null;
        try{
            // 读取图片文件
            is = new FileInputStream(srcpath);
            Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(suffix);
            ImageReader reader = it.next();
            // 获取图片流
            iis = ImageIO.createImageInputStream(is);
            reader.setInput(iis, true);
            ImageReadParam param = reader.getDefaultReadParam();
            Rectangle rect = new Rectangle(x, y, width, height);
            // 提供一个 BufferedImage，将其用作解码像素数据的目标。
            param.setSourceRegion(rect);
            BufferedImage bi = reader.read(0, param);
            // 保存新图片
            ImageIO.write(bi, suffix, new File(subpath));
        }
        finally{
            if(is != null)
                is.close();
            if(iis != null)
                iis.close();
        }
    }

    public static void main(String[] args){
        try{
            // ImageUtil.cut("E://test1.jpg", "E://test2.jpg", 0, 0, 500, 300,
            // "jpg");
            File file = new File("E://zoom2.jpg");
            File file1 = new File("E://test1.jpg");
            BufferedImage buff = ImageIO.read(file1);
            ImageUtil.zoom(buff, file, 768, 768);

        }
        catch(IOException e){
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}